package com.ziytek.web.citizen.service.impl;

import cn.idev.excel.util.StringUtils;
import com.google.gson.Gson;
import com.ziytek.web.citizen.configuration.RefreshSqliteConfiguration;
import com.ziytek.web.citizen.constant.NumConstant;
import com.ziytek.web.citizen.constant.TableConstant;
import com.ziytek.web.citizen.mapper.BoardConfigMapper;
import com.ziytek.web.citizen.mapper.HistoryTableMapper;
import com.ziytek.web.citizen.mapper.TableMapper;
import com.ziytek.web.citizen.model.req.SingleBatteryCellReq;
import com.ziytek.web.citizen.model.rsp.SingleBatteryCellRsp;
import com.ziytek.web.citizen.model.vo.RealTimeVo;
import com.ziytek.web.citizen.model.vo.StatsDo;
import com.ziytek.web.citizen.service.CompressionService;
import com.ziytek.web.citizen.service.itf.SingleBatteryCellService;
import com.ziytek.web.citizen.util.CabinetNoUtil;
import com.ziytek.web.citizen.util.DateTimeUtils;
import com.ziytek.web.citizen.util.NumberToUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @className SingleBatteryCellServiceImpl
 * @description: 实时曲线单个电芯最后一条电压电流数据服务实现类
 * @jdkVersion: 1.8
 * @author: fhx
 * @date: 2024/7/2 9:53
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SingleBatteryCellServiceImpl implements SingleBatteryCellService {
    private final Gson gson;
    private final TableMapper tableMapper;
    private final BoardConfigMapper boardConfigMapper;
    private final HistoryTableMapper historyTableMapper;
    private final CompressionService compressionService;
    private final RefreshSqliteConfiguration refreshSqliteConfiguration;

    @Override
    public SingleBatteryCellRsp getSingleBatteryCell(SingleBatteryCellReq request) {
        var rsp = new SingleBatteryCellRsp();
        rsp.setRetSuccessData(NumConstant.INT_ZERO, NumConstant.INT_ZERO, NumConstant.FLOAT_ZER);

        if (StringUtils.isBlank(request.getDoor()) || StringUtils.isBlank(request.getCabinetNo())
                || null == request.getChannelNo() || null == request.getLineNo()) {
            return rsp;
        }

        var lineNo = request.getLineNo();
        var batchNoStr = request.getBatchNo();
        var cabinetNo = request.getCabinetNo();
        var channelNo = request.getChannelNo();

        var boardConfig = boardConfigMapper.queryByLineNo(lineNo, channelNo);
        if (null == boardConfig) {
            rsp.setRetErrorData("未查询到板子配置信息");
            return rsp;
        }

        // 先加载数据库，在切换数据库DB文件
        //RealTimeDo ro;
        StatsDo sdo;
        //var tableName = TableConstant.TABLE_REAL_TIME + boardConfig.getAddress();
        var statsTableName = TableConstant.TABLE_REAL_TIME_STATS;
        if (StringUtils.isNotBlank(batchNoStr)) {
            boolean isToday = DateTimeUtils.isToday(request.getBatchNo());
            var batchNo = batchNoStr.replaceAll("-", "").replaceAll(":", "").replaceAll(" ", "");

            if (isToday) {
                //ro = tableMapper.queryRealTimeLastAndBatchNo(tableName, Integer.parseInt(CabinetNoUtil.getCabinetNo(cabinetNo)), boardConfig.getAddress(),
                //boardConfig.getChannelNo(), batchNo);
                sdo = tableMapper.queryStatsDoLastByBatchNo(statsTableName, Integer.parseInt(CabinetNoUtil.getCabinetNo(cabinetNo)), boardConfig.getAddress(),
                        boardConfig.getChannelNo(), batchNo);
            } else {
                var dbName = "Data_" + batchNo.substring(NumConstant.INT_TWO, NumConstant.INT_EIGHT);
                log.info("切换历史数据库文件:{}", dbName);
                refreshSqliteConfiguration.updateYmlData("historyDbName", dbName);

                sdo = historyTableMapper.queryStatsDoLastByBatchNo(statsTableName, Integer.parseInt(CabinetNoUtil.getCabinetNo(cabinetNo)), boardConfig.getAddress(),
                        boardConfig.getChannelNo(), batchNo);
                //ro = historyTableMapper.queryRealTimeLastAndBatchNo(tableName, Integer.parseInt(CabinetNoUtil.getCabinetNo(cabinetNo)), boardConfig.getAddress(),
                //boardConfig.getChannelNo(), batchNo);
            }
        } else {
            //ro = tableMapper.queryRealTimeLast(tableName, Integer.parseInt(CabinetNoUtil.getCabinetNo(cabinetNo)), boardConfig.getAddress(), boardConfig.getChannelNo());
            sdo = tableMapper.queryStatsDoLastNoId(statsTableName, Integer.parseInt(CabinetNoUtil.getCabinetNo(cabinetNo)), boardConfig.getAddress(),
                    boardConfig.getChannelNo());
        }
        if (null == sdo) {
            //rsp.setRetErrorData("未查询到数据");
            log.info("实时曲线单个电芯最后一条容量数据未查询到数据:{}", gson.toJson(request));
            return rsp;
        }

        byte[] data;
        try {
            data = compressionService.decompress(sdo.getData());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        var v = gson.fromJson(new String(data, StandardCharsets.UTF_8), RealTimeVo.class);
        if (null == v) {
            //rsp.setRetErrorData("未查询到数据");
            log.info("实时曲线单个电芯最后一条容量数据解析RealTimeVo失败:{}", gson.toJson(request));
            return rsp;
        }

        rsp.setCapacity(NumberToUtils.doubleToFloat2Decimal(v.getCpa(), NumConstant.INT_TWO));
        rsp.setCurrent(v.getC());
        rsp.setVoltage(v.getV());
        return rsp;
    }
}
